#! /usr/bin/env python
# -*- coding: utf8 -*-

# Alexandre Coster <acoster@rhrk.uni-kl.de>
# AG DBIS - Technische Universität Kaiserslautern

import os
import sys
import os.path

def loadPlugins(path="Plugins", interface=None):
    """
    Loads plugins from all files from a given path. Those classes/objects/whatever
    (you choose what semantics you want to give to your plugins) should be listed on
    a sequence named __plugins__.

    This function can receive an optional interface, to test if the plugins implement
    this interface (and filter out stuff that doesn't implement it.)
    """
    classes = []

    if not os.path.isdir(path):
        raise IOError("Path is not a directory.")

    if path not in sys.path:
        sys.path.append(path)

    file_list = [x[:-3] for x in os.listdir(path) if x[-3:] ==".py" and x[:-3] != "__init__"]

    for i in file_list:
        m = __import__(i)

        try:
            map(classes.append, m.__plugins__)
        except AttributeError:
            pass

    if interface != None:
        classes = filter(lambda x:interface.implementedBy(x), classes)

    return classes
